import Request from '@/utils/luch-request/index.js'
import store from '@/store';

const storeId = 5; //商城应用Id,生成APP情况下需要配置

const baseUrl = 'https://www.nuopian.com';

const accessToken = () => {
	let userToken = {}
	if (store.state.accessToken) {
		userToken.access_token = store.state.accessToken;
	}
	try {
		uni.getStorage({
			key: "parent",
			success: (res) => {
				userToken.parent_id = res.data
			}
		})
	} catch (e) {
		
	}
	return userToken
}

const http = new Request();
http.setConfig((config) => {
	config.baseURL = baseUrl;
	config.header = {
		...config.header,
		'Content-Type': 'application/json;charset=UTF-8',
		'Content-Type': 'application/x-www-form-urlencoded'
	}
	return config
});

http.interceptors.request.use((config) => {
	config.header = {
		...config.header,
	},
	config.params = {
		...config.params,
		// #ifdef H5
		platform: 'h5',
		domain: window.location.host,
		// #endif
		// #ifdef MP-WEIXIN
		platform: 'wechat',
		appid: uni.getAccountInfoSync().miniProgram.appId,
		// #endif
		// #ifdef MP-QQ
		platform: 'qq',
		appid: uni.getAccountInfoSync().miniProgram.appId,
		// #endif
		// #ifdef APP-PLUS
		platform: 'app',
		store_id: storeId,
		// #endif
		version: 2,
		...accessToken(),
	}
	return config
}, (config) => {
	return Promise.reject(config)
})

http.interceptors.response.use(
	async (response) => {
		switch (response.data.code) {
			case 200:
				return response.data.data;
				break;
			case 401:
				uni.showModal({
					content: "登录过期，请重新登录",
					confirmText: "去登录",
					success:(res)=>{
						if (res.confirm) {
							uni.navigateTo({
								url: "/pages/public/login"
							});
						}
					}
				})
				return Promise.reject(response.data);
				break;
			case 402:
				uni.removeStorageSync('indexData');
				uni.showModal({
					content: "应用到期，请续费后重试！",
					showCancel: false
				})
				return Promise.reject(response.data);
				break;
			case 422:
				return Promise.reject(response.data);
				break;
			default:
				return response.data.data;
		}
	},
	(response) => {
		return Promise.reject(response);
	}
);

export { http };